import axios from 'axios'
import { Post, Category } from '@/types'

const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001'

const api = axios.create({
  baseURL: API_URL,
  timeout: 10000,
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// API 方法
export const apiClient = {
  // 获取帖子列表
  getPosts: (params?: {
    category?: number
    sort?: string
    order?: 'ASC' | 'DESC'
    limit?: number
    offset?: number
  }) => api.get<Post[]>('/api/posts', { params }),

  // 获取帖子详情
  getPost: (id: number) => api.get<Post>(`/api/posts/${id}`),

  // 获取版块列表
  getCategories: () => api.get<Category[]>('/api/categories'),

  // 创建帖子
  createPost: (data: {
    title: string
    content: string
    categoryId: number
  }) => api.post<Post>('/api/posts', data),

  // 用户相关
  login: (data: { email: string; password: string }) =>
    api.post('/api/auth/login', data),
    
  register: (data: { username: string; email: string; password: string }) =>
    api.post('/api/auth/register', data),
}

export default api
